package android_serialport_api.sample;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jlupgrade.R;
import com.jl.update.HardwareUpdate;

import com.util.CMD_Manager;
import com.util.EncodingUtil;

/**
 * 聚利2升级程序
 *
 * @author LiuYaDong
 */
public class UpgradeActivity extends Activity {

    public static UpgradeHandle handler = null;
    public static String path = "";
    private List<String> allCounties = null;
    private ArrayAdapter<String> countiesAdapter;
    private Spinner file = null;
    private LayoutInflater inflater = null;
    private ProgressBar prb = null;
    private TextView prbText = null;
    private TextView baifenbi = null;
    private TextView version = null;
    private AlertDialog alertDialog = null;
    private CMD_Manager manager;

    String path2 = "/sys/bus/platform/drivers/mediatek-pinctrl/10005000.pinctrl/mt_gpio";
    String pathT80 = "/sys/class/ETC/ETC/power5v_open";
    BufferedWriter CtrlFile;

    File DeviceName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actiity_upgrade);


        API.type = getSystemModel();
        initRoot();
        switch (API.type) {
            case "SD100":
                DeviceName = new File(path2);
                break;
            case "FOT":
                DeviceName = new File(path2);
                break;
            case "T80":
                DeviceName = new File(pathT80);
                break;

            default:
                break;
        }

        try {
            CtrlFile = new BufferedWriter(new FileWriter(DeviceName, false));
        } catch (IOException e3) {
            e3.printStackTrace();
        }


//        powerOn();

        manager = CMD_Manager.getCMDManager();
        // 保持屏幕长亮
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        @SuppressWarnings("deprecation")
        PowerManager.WakeLock mWakeLock = pm.newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        mWakeLock.acquire();
        mWakeLock.release();
        handler = new UpgradeHandle();
        TextView tv = (TextView) findViewById(R.id.messages);
        Button shangdian = (Button) findViewById(R.id.shangdian);
        shangdian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                powerOn();
            }
        });
        Button xiadian = (Button) findViewById(R.id.xiadian);
        xiadian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                powerOff();
            }
        });
        tv.setText("版本号：" + getVersion() + "\njl2升级程序");
        version = (TextView) findViewById(R.id.textView1);


    }

    private void initRoot() {
        PrintWriter PrintWriter = null;
        Process process = null;
        try {
//			process = Runtime.getRuntime().exec("su");
            process = Runtime.getRuntime().exec("sh");

            PrintWriter = new PrintWriter(process.getOutputStream());
            PrintWriter.flush();
            PrintWriter.close();
            int value = process.waitFor();
            Toast.makeText(getApplicationContext(), "获取ROOT权限成功", Toast.LENGTH_LONG).show();
            // return returnResult(value);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "获取ROOT权限失败", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        // return false;
    }

    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        init();
    }

    /**
     * 装载文件进入下拉列表
     */
    public void init() {                                        // /storage/sdcard0
        path = Environment.getExternalStorageDirectory() + ""; // /storage/sdcard0/JLST-HC_V1.03.jl2
        HardwareUpdate.fileName(path);
        allCounties = HardwareUpdate.list;
        if (allCounties == null || allCounties.size() == 0) {
            Toast.makeText(getApplicationContext(), "未能找到.jl2升级文件，请保证本地文件中存在.jl2文件后打开软件进行升级", Toast.LENGTH_LONG).show();
        }
        countiesAdapter = new ArrayAdapter<String>(UpgradeActivity.this,
                android.R.layout.simple_spinner_item, allCounties);
        countiesAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        file = (Spinner) findViewById(R.id.files);
        file.clearAnimation();
        file.setAdapter(countiesAdapter);

    }

    public void buttOnClick(View v) {
        switch (v.getId()) {
            case R.id.download:
                powerOff();
                powerOn();
                startDownLoad();
                break;
            case R.id.delete:
                android.os.Process.killProcess(android.os.Process.myPid());
                break;
            case R.id.button1:
                readVersion();
            default:
                break;
        }
    }

    Message message;

    public void readVersion() {
        version.setText("");
        new
                Thread(new Runnable() {
            @Override
            public void run() {
                String Result = null;
                try {
                    Result = manager.SendReadVersion();
                    Log.e("version ", "Result = " + Result);
                    String str = EncodingUtil.asciiToString(Result);
                    Log.e("test", "str->" + str);
                    message = handler.obtainMessage();
                    message.obj = "version:" + str;
                } catch (Exception e) {
                    e.printStackTrace();
                    message = handler.obtainMessage();
                    message.obj = "version:";
                }


                handler.sendMessage(message);
            }
        }).start();
//        new FunctionThread() {
//
//            @Override
//            public void function() throws Exception {
//
//            }
//
//            @Override
//            public void errorResult(Exception e) {
//                // TODO Auto-generated method stub
//
//            }
//        }.start();
    }

    public void startDownLoad() {
        if (file.getSelectedItem() == null) {
            Toast.makeText(getApplicationContext(), "您未选择升级文件", Toast.LENGTH_LONG).show();
            return;
        }
        inflater = LayoutInflater.from(UpgradeActivity.this);
        View textEntryView = inflater.inflate(
                R.layout.alert_dialog_progressbar_hardwareupdate, null);
        prb = (ProgressBar) textEntryView.findViewById(R.id.progress);
        prb.setMax(100);
        prb.setProgress(0);
        prbText = (TextView) textEntryView.findViewById(R.id.prbText);
        prbText.setText("");
        baifenbi = (TextView) textEntryView.findViewById(R.id.baifenbi);
        prbText.setText("0%");
        Builder dia = new AlertDialog.Builder(UpgradeActivity.this);
        dia.setIcon(R.drawable.dialog_bottom_bg);
        dia.setTitle("硬件升级进度");
        dia.setView(textEntryView);
        alertDialog = dia.create();
        alertDialog.setCancelable(false);
        alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false; // 默认返回 false
                }
            }
        });
        alertDialog.show();
        //HardwareUpgrade hu = new HardwareUpgrade(handler, "");
        HardwareUpdate hu = new HardwareUpdate();
        hu.setFileName(file.getSelectedItem().toString());
        hu.start();
    }

    public void showDialog() {
        new AlertDialog.Builder(UpgradeActivity.this)
                .setTitle("提示")
                .setMessage("不能自动复位，是否手动复位？")
                .setPositiveButton("是", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        powerOff();
                        powerOn();
                        dialog.dismiss();
                        HardwareUpdate.position = 2;
                        startDownLoad();
                        System.out.println("test show yes");
                    }
                })
                .setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        dialog.dismiss();
                        System.out.println("test show");
                    }
                }).show();
    }

    /**
     * 操作线程
     *
     * @author LiuYaDong
     */
    public abstract class FunctionThread extends Thread {

        public abstract void function() throws Exception;

        public abstract void errorResult(Exception e);

        @Override
        public void run() {
            try {
                function();
            } catch (Exception e) {
                errorResult(e);
            }
        }
    }

    /**
     * 接收消息Handler
     *
     * @author LiuYaDong
     */
    @SuppressLint("HandlerLeak")
    public class UpgradeHandle extends Handler {

        @Override
        public void handleMessage(Message msg) {
            String str = msg.obj.toString();
            if (str.contains("version")) {
                version.setText(str);
            } else if (msg.arg1 == 0) {
                prbText.setText(str);
            } else if (msg.arg1 == 24) {
                prb.setProgress(Integer.parseInt(str.substring(0, str.length() - 1)));
                baifenbi.setText(str);
            } else if (msg.arg1 == 23) {
                prbText.setText(str);
            } else if (msg.arg1 == 2) {
                if (alertDialog != null) {
                    alertDialog.dismiss();
                    Toast.makeText(UpgradeActivity.this, "升级失败：" + str, Toast.LENGTH_LONG).show();
                }
            } else if (msg.arg1 == 3) {
                if (alertDialog != null) {
                    alertDialog.dismiss();
                    Toast.makeText(UpgradeActivity.this, str, Toast.LENGTH_LONG).show();
                }
            } else if (msg.arg1 == 1) {
                if (alertDialog != null)
                    alertDialog.dismiss();
                showDialog();
            }
            super.handleMessage(msg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        powerOff();
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }


    private void powerOn() {
        switch (API.type) {
            case "SD100":
                power10On();
                break;
            case "FOT":
                powerFOTOn();
                break;
            case "T80":
                powerT80On();
                break;
            default:
                break;
        }


    }

    private void powerOff() {
        switch (API.type) {
            case "10":
                power10Off();
                break;
            case "FOT":
                power8Off();
                break;
            case "T80":
                powerT80Off();
                break;
            default:
                break;
        }

    }


    private void power10Off() {
        try {
            CtrlFile.write("out 52 0");
            CtrlFile.flush();
            Toast.makeText(UpgradeActivity.this, "下电成功", Toast.LENGTH_SHORT)
                    .show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void power10On() {
        try {

            CtrlFile.write("out 52 1");
            CtrlFile.flush();
            CtrlFile.write("mode 52 0");
            CtrlFile.flush();
            CtrlFile.write("dir 52 1");
            CtrlFile.flush();

            Toast.makeText(UpgradeActivity.this, "上电成功", Toast.LENGTH_SHORT)
                    .show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void power8Off() {
        try {
            CtrlFile.write("set 6 010");
            CtrlFile.flush();
            CtrlFile.write("set 7 010");
            CtrlFile.flush();
            CtrlFile.write("set 24 010");
            CtrlFile.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void powerFOTOn() {
        try {
//			powerflag = true;
            CtrlFile.write("set 6 011");
            CtrlFile.flush();
            CtrlFile.write("set 7 011");
            CtrlFile.flush();
            CtrlFile.write("set 24 011");
            CtrlFile.flush();
            Toast.makeText(UpgradeActivity.this, "上电成功", Toast.LENGTH_SHORT)
                    .show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void powerT80On() {
        try {
            CtrlFile.write("1");
            CtrlFile.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void powerT80Off() {
        try {
            CtrlFile.write("0");
            CtrlFile.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
